package j20251027;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private int serverPort;
    private String serverIp;
    private DatagramSocket socket=null;
    public UdpEchoClient(int serverPort, String serverIp) throws SocketException {
        this.serverPort = serverPort;
        this.serverIp = serverIp;
        socket=new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while(true){
            System.out.println("请输入请求：");
            String request=scanner.next();
            if(!scanner.hasNextLine()){
                break;
            }
            //1.将请求传给服务端
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            //2.从服务端获取响应
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response=new String(responsePacket.getData(),0,
                    responsePacket.getLength());
            //3.打印响应
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient(9090, "127.0.0.1");
        client.start();
    }
}
